#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import socket
import urllib
import os

import config
from logger import logger
import utils

socket.setdefaulttimeout(5.0)


class Downloader(object):
    def __init__(self):
        super(Downloader, self).__init__()
        self._cache_dir = config.CACHE_DIR
        self._download_dir = config.DOWNLOAD_DIR
        self._is_running = False

        utils.check_dir(self._cache_dir)
        utils.check_dir(self._download_dir)

    def add_task(self, song, flag=0):
        if self._is_running:
            logger.info("Task is running: %s" % self._current_file)
            return
        self._is_running = True
        results = True
        logger.info('Start %s Song: %s' % (flag == 0 and 'Cache' or 'Download',
                                           song.mp3_file))
        self._current_file = flag == 0 and os.path.join(
            self._cache_dir, song.mp3_file) or os.path.join(self._download_dir,
                                                            song.mp3_file)
        try:
            if not os.path.exists(self._current_file):
                urllib.urlretrieve(song.play_url, self._current_file,
                                   self.show_progress)
        except Exception as e:
            results = False
            logger.error(e)
        self._is_running = False
        return results

    def show_progress(self, block, blocksize, filesize):
        """
        @block              size of downloaded file
        @blocksize          size of block
        @filesize           size of remote file
        """
        per = 100.0 * block * blocksize / filesize
        if per > 100:
            per = 100
        print('%.2f%%\r' % per, end='')

        if per == 100:
            logger.info('Download completed: %s' % self._current_file)


if __name__ == '__main__':
    d = Downloader()
